package com.chucknorris.android.ui;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.chucknorris.android.R;
import com.chucknorris.android.adapter.ChuckAdapter;
import com.chucknorris.android.db.ChuckColumns;
import com.chucknorris.android.db.ChuckQuery;
import com.chucknorris.android.model.Chuck;
import com.chucknorris.android.util.LocaleUtils;

public class ListFavourtesActivity extends GAActivity implements LoaderManager.LoaderCallbacks<Cursor>, OnItemClickListener {
	private ListView list;
	private Cursor mCursor;
	private ChuckAdapter adapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list);
		list = (ListView) findViewById(R.id.list);
		list.setOnItemClickListener(this);
		getSupportLoaderManager().initLoader(ChuckQuery._TOKEN, null, this);
	}

	@Override
	public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
		return new CursorLoader(ListFavourtesActivity.this, Chuck.CONTENT_URI, ChuckQuery.PROJECTION, ChuckColumns.ISLIKE.getName() + " =? AND "
				+ ChuckColumns.LOCALE.getName() + " = '" + LocaleUtils.getCurrentLocale() + "'", new String[] { String.valueOf(1) }, Chuck.DEFAULT_SORT);

	}

	@Override
	public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) {
		if (cursor.getCount() == 0) {
			finish();
			Toast.makeText(ListFavourtesActivity.this, getString(R.string.empty_list), Toast.LENGTH_SHORT).show();
		} else {
			mCursor = cursor;
			adapter = new ChuckAdapter(ListFavourtesActivity.this, cursor);
			list.setAdapter(adapter);
		}

	}

	@Override
	public void onLoaderReset(Loader<Cursor> loader) {

	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
		if (mCursor != null && mCursor.moveToPosition(position)) {
			Intent intent = new Intent();
			intent.putExtra("id", id);
			setResult(RESULT_OK, intent);
			finish();
		}
	}

}
